package fr.mywiki.model.jdbcAdapter.values;

import java.lang.reflect.Field;

/**
 * This facade deals with returning the correct class of object and some characteristic data about a
 * given type of data.
 * 
 * @author tlombard
 * 
 */
public class ValueObjectFacade {
	public static final String CLASS_PACKAGE = "fr.mywiki.model.jdbcAdapter.values";

	/**
	 * This method returns the ValueObject class corresponding to a specific data type given in
	 * parameter.
	 * 
	 * @param type a String object reprensenting the type of a ValueObject Object
	 * @return a Class object corresponding to the given type or <code>null</code> if this type
	 *         does not correspond to a type of data.
	 */
	private static Class getClass(String type) {
		if (EntryValue.TYPE.equals(type))
			return EntryValue.class;
		if (UserValue.TYPE.equals(type))
			return UserValue.class;
		return null;
	}

	/**
	 * Returns the complete path and name of the class corresponding to the type given in parameter.
	 * The result String can be used to call a class.
	 * 
	 * @param type the data type.
	 * @return a String being the name of a class or <code>null</code>.
	 */
	private static String getClassPathName(String type) {
		String classPackage = getPackage() + ".";
		String className = new String();
		if (EntryValue.TYPE.equals(type))
			className = "EntryValue";
		if (UserValue.TYPE.equals(type))
			className = "UserValue";

		if (className.length() == 0)
			return null;
		return classPackage + className;
	}

	/**
	 * Returns the package in which this class lies.
	 * 
	 * @return a String object describing the complete package (without the class name) of the class
	 *         <code>ValueObjectFacade</code>.
	 */
	private static String getPackage() {
		return CLASS_PACKAGE;
	}

	/**
	 * Computes and returns the name of the field which corresponds to the identifier of the given
	 * type.
	 * 
	 * @param type a String object : a data type.
	 * @return a String object.
	 */
	public static String getIdentifierFieldName(String type) {
		Class valueClass = getClass(type);
		String result = null;
		try {
			Field identifierField = valueClass.getField(AbstractValueObject.IDENTIFIER);
			result = (String) identifierField.get(Class.forName(getClassPathName(type)));
		} catch (Exception e) {}
		return result;
	}

	/**
	 * Returns the name of the class of the field which name is given in parameter, for the desired
	 * class.
	 * 
	 * @param dataType a dataType.
	 * @param fieldName a field name.
	 * @return a String representing the name of a Java type, <code>null</code> if it was not
	 *         found.
	 */
	public static String getFieldType(String dataType, String fieldName) {
		Class valueClass = getClass(dataType);
		String result = null;
		try {
			Field field = valueClass.getField(fieldName);
			result = field.getType().getName();
		} catch (Exception e) {}
		return result;
	}
}
